package com.demo.pattern.singleton;

/**
 * @author sourire
 * @version 1.0
 * @date 2020/8/17 16:53
 */
public class SingletonTest05 {
    public static void main(String[] args) {

        SingleTon05 instance = SingleTon05.getInstance();
        SingleTon05 instance2 = SingleTon05.getInstance();
        System.out.println(instance == instance2);
        System.out.println("instance === " + instance.hashCode());
        System.out.println("instance2 === " + instance2.hashCode());
    }
}

//双重检查

class SingleTon05 {
    //构造器私有化
    private SingleTon05() {
    }
    //初始化静态常量
    private  static volatile SingleTon05 instance ;
    //对外提供静态的调用方法
    public static  SingleTon05 getInstance() {
        //在调用的时候才初始化 懒加载
        if(instance == null){
            //同步代码块  双重判断 效率高
            synchronized (SingleTon05.class){
                if(instance == null){
                    instance = new SingleTon05();
                }
            }
        }
        return instance;
    }
}
